package juc.tools;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Package juc.lern.core
 * @ClassName CompletableFutureTest
 * @Description
 * @Author yangxin
 * @Email yangxin_xy@189.com
 * @Date 2022/2/2 3:20 下午
 */


public class CompletableFutureTest {

    public static void main(String[] args) throws Exception {
        /**
         * 不接受返回值,开启异步任务
         */
        CompletableFuture<String> completableFuture = CompletableFuture
                .supplyAsync(() -> "买入莱茵体育,第一天就涨停了")
                /**
                 * 接受返回值,使用当前线程继续执行
                 */
                .thenApplyAsync(r -> {
                    System.out.println(r);
                    return "买入莱茵体育,第二天又涨停了";
                })
                /**
                 * 接受返回值,开启新线程执行
                 */
                .thenComposeAsync(r -> CompletableFuture.supplyAsync(() -> {
                    System.out.println(r);
                    int a = 10 / 0;
                    return "买入莱茵体育第三天,又涨停了";
                }))
                /**
                 * 开启新的线程,接受当前结果和上一个结果
                 */
                .thenCombineAsync(CompletableFuture.supplyAsync(() ->
                        "有点慌了,第三个涨停还是卖了把"), (r1, r2) -> r1 + r2)
                /**
                 * 开启新的线程,获取之前线程的结果 看谁先执行完就返回谁
                 */
                .applyToEitherAsync(CompletableFuture.supplyAsync(() -> {
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "牛";
                }), r -> {
                    try {
                        System.out.println(r);
                        TimeUnit.SECONDS.sleep(4);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "逼!";
                })
                /**
                 * 获取结果
                 */
                .whenCompleteAsync((r, e) -> {
                    if (e == null) {
                        System.out.println("可以哇,没有发生异常!");
                        System.out.println(r);
                    }
                })
                /**
                 * 如果异常的话!
                 */
                .exceptionally(e -> {
                    e.printStackTrace();
                    System.err.println(e.getMessage());
                    return e.getMessage();
                });
        while (true) {

        }
    }
}
